package com.neuedu.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 金山
 * 项目：sca-all-in-one
 * site: https://blog.fulfill.com.cn
 * 描述  webflux  webmvc
 * @data 2025/6/39:40
 */
@Component
public class TokenFilter implements GlobalFilter {

    Logger log = LoggerFactory.getLogger(TokenFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // http://localhost:7000/mynew/pay?token=admin
        // http://localhost:7000/mynew/pay?token=abc
        // http://localhost:7000/old/pay
        log.info("校验 权限");
        // 判断是否存在token
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        log.info("token = " + token);
        if (!"admin".equals(token)) {
            log.info("验证token未通过");
            // 返回401

            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }


        log.info("验证token通过");
        // 验证token 通过了
        return chain.filter(exchange);


    }
}
